﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Qiniu.Storage;
using Qiniu.Util;
using Qiniu.Http;
using System.Linq;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http.Features;

namespace ThridGroup.ERP.Web.Controllers
{
    public class ImgController : Controller
    {
        private readonly ILogger<ImgController> _logger;

        public ImgController(ILogger<ImgController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [RequestSizeLimit(10 * 1024 * 1024)] // 10MB
        [RequestFormLimits(MultipartBodyLengthLimit = 10 * 1024 * 1024)]
        public async Task<IActionResult> UploadImg([FromForm]IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    _logger.LogError("No file was uploaded");
                    return Ok(new { code = 1, msg = "请选择要上传的文件" });
                }

                // 检查文件大小
                if (file.Length > 5 * 1024 * 1024) // 5MB
                {
                    _logger.LogError($"File size {file.Length} bytes exceeds limit of 5MB");
                    return Ok(new { code = 1, msg = "文件大小不能超过5MB" });
                }

                // 七牛云 AccessKey 和 SecretKey
                var accessKey = "9B0c2sKQXOBdrRvPDrb5UbT7E5pmt2SMNQfgbrX2";
                var secretKey = "FJvJd0JnJP_ngc_RJ7x3gJ6SrxkI1OYHt3rvGp-Nx";
                Mac mac = new Mac(accessKey, secretKey);

                // 保存路径
                string fileExtension = System.IO.Path.GetExtension(file.FileName);
                string saveKey = "MyFiles/Zhouheiya/" + System.DateTime.Now.Ticks + fileExtension;
                var fs = file.OpenReadStream();

                // 存储空间名
                string Bucket = "wangenenTest";

                // 上传策略
                PutPolicy putPolicy = new PutPolicy();
                putPolicy.Scope = Bucket;
                putPolicy.DeleteAfterDays = 100;

                try
                {
                    // 生成上传token
                    string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

                    // 配置
                    Config config = new Config();
                    config.Zone = Zone.ZONE_CN_North;
                    config.UseHttps = true;
                    config.UseCdnDomains = true;
                    config.ChunkSize = ChunkUnit.U512K;

                    // 数据流上传
                    FormUploader fu = new FormUploader(config);
                    var result = fu.UploadStream(fs, saveKey, token, null);
                    fs.Dispose();

                    if (result.Code != (int)HttpCode.OK)
                    {
                        _logger.LogError($"Qiniu upload failed: {result.Code} - {result.Text}");
                        return Ok(new { code = 1, msg = "上传失败：" + result.Text });
                    }

                    // 返回图片URL
                    var imgUrl = "http://sygwcc5qb.hb-bkt.clouddn.com/" + saveKey;
                    return Ok(new { code = 0, msg = "上传成功", data = imgUrl });
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Qiniu operation error: {ex.Message}");
                    return Ok(new { code = 1, msg = "七牛云操作失败：" + ex.Message });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Unexpected error in UploadImg: {ex.Message}");
                return Ok(new { code = 1, msg = "上传过程发生错误：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> QiniuDeleteFile(string url)
        {
            try
            {
                if (string.IsNullOrEmpty(url))
                {
                    return Ok(new { code = 1, msg = "URL不能为空" });
                }

                // 七牛云 AccessKey 和 SecretKey
                var accessKey = "9B0c2sKQXOBdrRvPDrb5UbT7E5pmt2SMNQfgbrX2";
                var secretKey = "FJvJd0JnJP_ngc_RJ7x3gJ6SrxkI1OYHt3rvGp-Nx";
                Mac mac = new Mac(accessKey, secretKey);

                // 存储空间名
                string Bucket = "wangenenTest";

                // 保存到七牛云上的文件目录
                url = url.Split('/').Last();
                string saveKey = "MyFiles/Zhouheiya/" + url;

                // 配置
                Config config = new Config();
                config.Zone = Zone.ZONE_CN_North;

                BucketManager bucketManager = new BucketManager(mac, config);
                HttpResult deleteRet = bucketManager.Delete(Bucket, saveKey);

                if (deleteRet.Code == (int)HttpCode.OK)
                {
                    return Ok(new { code = 0, msg = "删除成功", data = 1 });
                }
                else
                {
                    _logger.LogError($"Failed to delete file: {deleteRet.Code} - {deleteRet.Text}");
                    return Ok(new { code = 1, msg = "删除失败：" + deleteRet.Text, data = 0 });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error in QiniuDeleteFile: {ex.Message}");
                return Ok(new { code = 1, msg = "删除过程发生错误：" + ex.Message });
            }
        }
    }
}
